package org.linkerproject;

import java.io.UnsupportedEncodingException;

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.linkerproject.browser.BrowserManager;
import org.linkerproject.server.LocalServer;

public class Core {

	public static void main(String args[]) {
		String path = Core.getPath();

		// Server server = new Server(path);
		// server.start();

		Display display = new Display();
		Shell shell = new Shell(display);

		LocalServer localServer = new LocalServer(path);

		new BrowserManager(shell, path, localServer);

		shell.pack();
		shell.setMaximized(true);
		shell.open();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		display.dispose();
		// server.stopServer();
		System.exit(0);
	}

	private static String getPath() {
		String path = "";

		// 获得imLinker.jar文件所在文件夹
		String linkerClassPath = Core.class.getResource("").toString();
		int index = linkerClassPath.indexOf(".jar");

		// 打包后的情况
		if (index >= 0) {
			int start = index - 1;
			while (Character.isLetter(linkerClassPath.charAt(start))) {
				start--;
			}
			String jarName = linkerClassPath.substring(start + 1, index + 4);

			if (System.getProperty("os.name").startsWith("Linux")) {
				path = linkerClassPath;
				path = path.substring(path.indexOf("/"), path.indexOf(jarName));
			} else if (System.getProperty("os.name").startsWith("Windows")) {
				path = linkerClassPath;
				path = path.substring(path.indexOf("file:") + 5, path
						.indexOf(jarName));
			}

			try {
				path = java.net.URLDecoder.decode(path, "utf-8");
			} catch (UnsupportedEncodingException e) {
				System.out.println("decode path to utf-8 failed");
			}

		} else {
			// 编辑代码时的情况
			path = linkerClassPath.substring(linkerClassPath.indexOf("/"),
					linkerClassPath.indexOf("/bin"));
		}

		return path;
	}

}
